package com.basker.pisces.domain.element.resouce;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.basker.pisces.core.resource.IResourceLoader;
import com.basker.pisces.domain.element.MetaTypeManager;

//@ResouceHandler(order = Integer.MAX_VALUE, locationPatterns = "classpath*:**/metatype/builder/*.xml")
public class MetaTypeResouceHandler implements IResourceLoader, InitializingBean {

    /**
     * 内置的文本资源
     */
    private Set<String> buildInResources;

    @Autowired
    private ResourcePatternResolver resolver;

    @Override
    public void afterPropertiesSet() throws Exception {
        loadBuildInResources();
    }

    @Override
    public void load(Resource[] resources) throws IOException {
        if (buildInResources != null) {
            resources = Stream.of(resources).filter(res -> !buildInResources.contains(res.toString()))
                    .toArray(s -> new Resource[s]);
        }

        MetaTypeManager.build(resources);
    }

    private void loadBuildInResources() throws IOException {
        Resource[] resources = resolver.getResources("classpath*:**/metatype/builder/*pisces*.xml");

        if (resources.length > 0) {
            MetaTypeManager.build(resources);

            this.buildInResources = Stream.of(resources).map(res -> res.toString()).collect(Collectors.toSet());
        }
    }

}
